package com.jumi.microservice.rocketmq.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jumi.microservice.constant.StatusEnum;
import com.jumi.microservice.domain.Account;
import com.jumi.microservice.domain.Log;
import com.jumi.microservice.domain.Priority;
import com.jumi.microservice.domain.temp.DepartmentTemp;
import com.jumi.microservice.mapper.AccountMapper;
import com.jumi.microservice.mapper.DepartmentMapper;
import com.jumi.microservice.mapper.LogMapper;
import com.jumi.microservice.mapper.PriorityMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * - - - - - - - - - - - - - - -
 *
 * @author liuz
 * @date 2020/7/25 10:07
 * ToDoSomeThing
 * - - - - - - - - - - - - - - -
 */
@Component
public class Mqlistener  implements MessageListener {

    private static final Logger log = LoggerFactory.getLogger(Mqlistener.class);

    private LogMapper logMapper;

    private DepartmentMapper departmentMapper;

    private AccountMapper accountMapper;

    private  PriorityMapper priorityMapper;


    public Mqlistener(LogMapper logMapper, DepartmentMapper departmentMapper, AccountMapper accountMapper, PriorityMapper priorityMapper){
        this.logMapper = logMapper;
        this.departmentMapper = departmentMapper;
        this.accountMapper = accountMapper;
        this.priorityMapper = priorityMapper;
    }

    public LogMapper getLogMapper() {
        return logMapper;
    }

    public void setLogMapper(LogMapper logMapper) {
        this.logMapper = logMapper;
    }

    public DepartmentMapper getDepartmentMapper() {
        return departmentMapper;
    }

    public void setDepartmentMapper(DepartmentMapper departmentMapper) {
        this.departmentMapper = departmentMapper;
    }

    public AccountMapper getAccountMapper() {
        return accountMapper;
    }

    public void setAccountMapper(AccountMapper accountMapper) {
        this.accountMapper = accountMapper;
    }

    public PriorityMapper getPriorityMapper() {
        return priorityMapper;
    }

    public void setPriorityMapper(PriorityMapper priorityMapper) {
        this.priorityMapper = priorityMapper;
    }

    //
////    @Override
////    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
////        // msgs中只收集同一个topic，同一个tag，并且key相同的message
////        // 会把不同的消息分别放置到不同的队列中
////        try {
////            for (Message msg : list) {
////                log.info("Consumer-获取消息={}",msg);
////                String body = new String(msg.getBody(), "utf-8");
////                log.info("Consumer-获取消息-主题topic为={}, 消费消息为={}", msg.getTopic(), body);
////                if(StringUtils.isNotEmpty(body)){
////                    Log log = JSONObject.toJavaObject(JSONObject.parseObject(body), Log.class);
////                    saveLog(log);
////                }
////            }
////        } catch (UnsupportedEncodingException e) {
////            e.printStackTrace();
////            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
////        }
////        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
////    }

    /**
     * 保存log日志
     * @param log
     */
    private void saveLog(Log log){
        //先获取用户信息
        Account ac = accountMapper.selectOne(
                Wrappers.<Account>lambdaQuery()
                        .eq(Account::getUid,log.getAccountId())
                        .eq(Account::getStatus, StatusEnum.STATUS_YES.getCode())
                        .eq(Account::getIsDel,StatusEnum.STATUS_NO.getCode()));
        if(ac!=null) {
            log.setUserName(ac.getUserName());
            log.setDepartmentId(ac.getDepartmentId());
            log.setMobile(ac.getMobile());
            log.setDepartmentName(getDepName(ac.getDepartmentId()));
        }
        //获取操作菜单信息
        if(StringUtils.isNotEmpty(log.getPriorityName())) {
            Priority p = priorityMapper.selectOne(
                    Wrappers.<Priority>lambdaQuery()
                            .eq(Priority::getPriorityCode,log.getPriorityName())
                            .eq(Priority::getIsDel, StatusEnum.STATUS_NO.getCode())
                            .eq(Priority::getStatus,StatusEnum.STATUS_YES.getCode()));
            if(p!=null){
                String psname = p.getPriorityName();
                //获取父级菜单目录
                String pname = priorityMapper.selectParentMenuById(p.getId());
                //拼接父菜单信息
                if(StringUtils.isNotEmpty(pname)){
                    if(pname.contains(",")) {
                        pname = pname.replace(",", "->") + "->" + psname;
                    }else{
                        pname = pname+"->"+psname;
                    }
                }
                log.setPriorityName(pname);
            }
        }
        //如果是批量操作 修改为多条记录
        if(StringUtils.isNotEmpty(log.getPriorityId())&&log.getPriorityId().contains(",")){
            String[] ids = log.getPriorityId().split(",");
            Arrays.stream(ids).forEach(id->{
                log.setPriorityId(id);
                logMapper.insert(log);
                log.setId(null);
            });
        }else {
            logMapper.insert(log);
        }
    }

    /**
     * 获取无限上级部门名称
     * @param depid 当前部门id
     * @return
     */
    private String getDepName(Long depid){
       StringBuilder sb = new StringBuilder();
       //获取无线上级部门
       List<DepartmentTemp> list = departmentMapper.selectParentDep(depid);
       list.stream().forEach(d->{
           sb.append(d.getDepartmentName());
           //不为最后低级部门继续添加 ->
           if(list.indexOf(d)!=list.size()-1) {
               sb.append("->");
           }
       });
        return sb.toString();
    }

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        try {
            log.info("Consumer-获取消息={}",message);
            String body = new String(message.getBody(), "utf-8");
            log.info("Consumer-获取消息-主题topic为={}, 消费消息为={}", message.getTopic(), body);
            if(StringUtils.isNotEmpty(body)){
                Log log = JSONObject.toJavaObject(JSONObject.parseObject(body), Log.class);
                saveLog(log);
            }
            return Action.CommitMessage;
        }catch (Exception e){
            e.printStackTrace();
            log.info("Consumer-获取消息-保存异常={}", JSONObject.toJSONString(e));
            return Action.ReconsumeLater;
        }
    }
}
